<template>
  <el-dialog
      title="上传流程"
      :model-value="modelValue"
      width="30%"
      :before-close="handleClose"
      destroy-on-close>
    <el-form :model="form" label-width="100px">
      <el-form-item label="流程名称">
        <el-input v-model="form.processName"></el-input>
      </el-form-item>
      <el-form-item>
        <UploadComponent @upload-success="handleFileUploaded" @upload-remove="handleFileRemoved" @file-success-multipartFile="handleFileUploadedByMultipartFile"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="submitUpload">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref } from 'vue';
import UploadComponent from '@/components/FileUpload/UploadComponent.vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { deployProcess } from "@/api/workflow/processManager.js";

const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  }
});

const emit = defineEmits(['update:modelValue']);

const form = ref({
  processName: '',
  processBpmnFile: null,
});
const isFileUploaded = ref(false);

// 处理文件上传成功的回调
const handleFileUploaded = (uploadRes) => {
};

const handleFileUploadedByMultipartFile = (uploadRes) => {
  console.log('文件上传成功:', uploadRes)
  form.value.processBpmnFile = uploadRes;
  isFileUploaded.value = true;
};

// 处理文件移除的回调
const handleFileRemoved = () => {
  form.value.processBpmnFile = null;
  isFileUploaded.value = false;
};

// 处理取消
const handleCancel = () => {
  emit('update:modelValue', false);
};

// 处理对话框关闭
const handleClose = (done) => {
  ElMessageBox.confirm('确认关闭？')
    .then(() => {
      form.value.processName = '';
      form.value.processBpmnFile = null;
      isFileUploaded.value = false;
      emit('update:modelValue', false);
      done();
    })
    .catch(() => {
      // 取消关闭
    });
};

// 提交表单
const submitUpload = () => {
  if (!form.value.processName) {
    ElMessage.error('请输入流程名称');
    return;
  }
  if (!form.value.processBpmnFile || !form.value.processBpmnFile.file) {
    ElMessage.error('请选择文件');
    return;
  }

  // 构造 FormData
  const formData = new FormData();
  formData.append('name', form.value.processName); // 后端需要的参数名是 name
  formData.append('file', form.value.processBpmnFile.file); // 后端需要的参数名是 file

  // 调用部署流程接口
  deployProcess(formData)
      .then((deployRes) => {
        if (deployRes.code === 200) {
          ElMessage.success('流程部署成功');
          emit('update:modelValue', false);
        } else {
          ElMessage.error(deployRes.msg || '流程部署失败');
        }
      })
      .catch((err) => {
        console.error('部署失败:', err);
        ElMessage.error('流程部署失败');
      });
};

</script>
